package com.gxsyh.nantie.order.consumer.controller;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.order.consumer.controller.dto.CreateOrderDTO;
import com.gxsyh.nantie.order.consumer.controller.dto.CreateOrderParam;
import com.gxsyh.nantie.order.consumer.utils.PingyinUtils;
import com.gxsyh.nantie.order.provider.*;
import com.gxsyh.nantie.order.provider.domain.TbDepartment;
import com.gxsyh.nantie.order.provider.domain.TbOrder;
import com.gxsyh.nantie.order.provider.domain.TbSubsidy;
import okhttp3.ResponseBody;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/2/21
 * @time: 14:53
 * @Description:
 */
@Transactional
@RestController
public class CreateOrderController {
    @Reference(version = "1.0.0")
    TbSubsidyService tbSubsidyService;

    @Reference(version = "1.0.0")
    TbOrderService tbOrderService;

    @Reference(version = "1.0.0")
    TbDepartmentService tbDepartmentService;

    @Reference(version = "1.0.0")
    TbDepartmentOrderService tbDepartmentOrderService;

    @Reference(version = "1.0.0")
    TbUserOrderService tbUserOrderService;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @Resource
    RedissonClient redissonClient;

    @PostMapping(value = "/order/create/add/from")
    public ResponseResult<CreateOrderDTO> createOrder(@RequestBody CreateOrderParam createOrderParam) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        boolean TimeOnSubsidyResult = tbSubsidyService.selectTimeOnSubsidy(createOrderParam.getSubsidyId());

        if (TimeOnSubsidyResult==false)
        {
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"补贴不在这个时间段内",null);
        }

        TbSubsidy tbSubsidy = tbSubsidyService.selectSubsidy(createOrderParam.getSubsidyId());

        ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "discuss").body();
        Long id = Long.valueOf(body.string());
        TbOrder tbOrder=new TbOrder();
        tbOrder.setId(id);
        tbOrder.setAmountConsumption(Double.parseDouble(createOrderParam.getMoney()));
        tbOrder.setCreatetime(new Date());
        tbOrder.setOrderStatus(1);
        tbOrder.setPayStatus(0);
        tbOrder.setPayMethod(null);
        tbOrder.setPayDepartmentId(createOrderParam.getDepartmentId());
        tbOrder.setSubsidy(tbSubsidy.getSubsidyMoney());

        RAtomicLong atomicLong = redissonClient.getAtomicLong(createOrderParam.getDepartmentId() + "_OrderNum");
        long l = atomicLong.incrementAndGet();
        long ttl = atomicLong.remainTimeToLive();
        if (ttl==-1)
        {
            atomicLong.expire(12, TimeUnit.HOURS);
        }

        DateTimeFormatter formatteryyyy = DateTimeFormatter.ofPattern("yyyy");
        int nowyyyy = Integer.parseInt(LocalDateTime.now(ZoneOffset.of("+8")).format(formatteryyyy));

        DateTimeFormatter formatterMM = DateTimeFormatter.ofPattern("MM");
        int nowMM = Integer.parseInt(LocalDateTime.now(ZoneOffset.of("+8")).format(formatterMM));

        DateTimeFormatter formatterdd = DateTimeFormatter.ofPattern("dd");
        int nowdd = Integer.parseInt(LocalDateTime.now(ZoneOffset.of("+8")).format(formatterdd));

        String pinyinString = PingyinUtils.getPinyinString(tbSubsidy.getName());
        CharSequence charSequence = pinyinString.subSequence(0, 1);

        String subName=null;
        if (charSequence.toString()!=null)
        {
            subName=charSequence.toString();
        }
        else
        {
            String name = tbSubsidy.getName();
            CharSequence charSequenceName = name.subSequence(0, 1);
            subName=charSequenceName.toString();
        }

        tbOrder.setOrderNum(l+"-"+nowyyyy+nowMM+nowdd+"-"+subName.toUpperCase()+l);




            CreateOrderDTO createOrderDTO=new CreateOrderDTO();
            TbDepartment tbDepartment = tbDepartmentService.selectOneByDepartmentId(Long.valueOf(createOrderParam.getDepartmentId()));
            createOrderDTO.setOrderId(id);
            createOrderDTO.setDepartment(tbDepartment.getName());
            createOrderDTO.setMoney(Double.parseDouble(createOrderParam.getMoney()));
            createOrderDTO.setSubsidyMoney(tbSubsidy.getSubsidyMoney());
            //支付
            String money = moneyYuanToFen(createOrderParam.getMoney());
            //补贴
            String subsidy = moneyYuanToFen(tbSubsidy.getSubsidyMoney().toString());

            BigDecimal bigDecimalMoney = new BigDecimal(money);
            BigDecimal bigDecimalSubsidy = new BigDecimal(subsidy);
            //相减
            BigDecimal paymentAmount = bigDecimalMoney.subtract(bigDecimalSubsidy);
            //分转元
            String paymentAmounts = moneyFenToYuan(paymentAmount.longValue());
            createOrderDTO.setPaymentAmount(paymentAmounts);
            tbOrder.setRemark(paymentAmounts);
            tbOrder.setMeal(tbSubsidy.getName());

            int order = tbOrderService.createOrder(tbOrder);
        TbDepartment inster = tbDepartmentService.selectOneByUserId(Long.valueOf(authentication.getName()));
        int resultDepartment = tbDepartmentOrderService.insterDepartmentOrder(id,inster.getId(),id);
        int resultUser = tbUserOrderService.insterUserOrder(id, Long.valueOf(authentication.getName()), id);
        createOrderDTO.setRepast(l);
            if (order>0&&resultDepartment>0&&resultUser>0){
                return new ResponseResult<>(HttpStatus.OK.value(),"增加订单成功",createOrderDTO);
            }
        return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"增加失败",null);
    }


    /**
     * 将元变成分 如 0.01元 变成 1分
     *
     * @param str 金额（元）
     * @return
     */
    public static String moneyYuanToFen(String str) {
        Double num = Double.parseDouble(str);
        int result = (int) (num * 100);
        return String.valueOf(result);

    }

    /**
     * 将分变成元 100分 -> 1元
     *
     * @param amount 金额（分）
     * @return
     */
    public static String moneyFenToYuan(Long amount) {
        return new BigDecimal(amount).divide(new BigDecimal(100)).setScale(2).toString();
    }


}
